<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace VeCongTy\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;

class TabController extends AbstractActionController
{
    protected $tabsTable;
    
    public function getTabsTable()
    {
        if(!$this->tabsTable)
        {
            $this->tabsTable = $this->getServiceLocator()->get('VeCongTy\Model\TabsTable');
        }
        
        return $this->tabsTable;
    }


    public function indexAction()
    {
        if($this->request->isXmlHttpRequest())
        {
            $tabs = $this->getTabsTable()->getAll();
            return new JsonModel(array(
                    'success' => 'true',
                    'tabs' => $tabs
            ));
        }
        else
        {
            return array();
        }
    }

    public function addTabAction()
    {
        if($this->request->isXmlHttpRequest())
        {
            $data = $this->params()->fromPost();
            if($this->getTabsTable()->isExist($data['key_name'], $data['name']))
            {
                return new JsonModel(array(
                    'success' => 'failed',
                    'msg' => 'Key name or tab name has already existed'
                ));
            }
            else
            {
                $this->getTabsTable()->addTab($data);

                return new JsonModel(array(
                    'success' => 'true'
                ));
            }
        }
        else
        {
            return array();
        }
    }
    
    public function saveValueAction()
    {
        if($this->request->isXmlHttpRequest())
        {
            $data = $this->params()->fromPost();
            
            $this->getTabsTable()->save($data['value'], $data['key_name']);
                    
            return new JsonModel(array(
                    'success' => 'true'
                ));
        }
        else
        {
            return array();
        }
    }
    
    public function removeTabAction()
    {
        if($this->request->isXmlHttpRequest())
        {
            $key_name = $this->params()->fromPost('key_name');
            
            $this->getTabsTable()->deleteTab($key_name);
                    
            return new JsonModel(array(
                    'success' => 'true'
                ));
        }
        else
        {
            return array();
        }
    }
}
